# import socket
#
# # AF_INET IPV4    SOCK_STREAM TCP通信
# client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#
# # 连接到指定服务器
# SERVER_INFO = ("192.168.11.157", 60000)
# client_socket.connect(SERVER_INFO)
#
# # 发送消息
# send_msg = input("输入发送内容")
# send_bytes = send_msg.encode("gbk")
# client_socket.send(send_bytes)
#
#
# recv_bytes = client_socket.recv(1024)
# recv_msg = recv_bytes.decode("gbk")
# print(f"收到{recv_msg}")
#
# client_socket.close()
# print(f"程序结束了")

import threading

def t_recv_main(client_socket):
    global connected
    # 接受消息
    while True:
        try:
            recv_bytes = client_socket.recv(1024)
            if len(recv_bytes) == 0:
                connected = False
                print(f"已经断开", connected)
                break
            recv_msg = recv_bytes.decode("gbk")
            print(f"收到消息{recv_msg}")
        except ConnectionAbortedError as e:
            print(f"停止接受消息")
            break
        except OSError as e:
            print(f"停止接受消息，链接关闭")
            break


import socket

# 确定是否正常连接
connected = False
def main():
    global connected
    # 构建客户端套接字实例
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    try:
        # 链接服务器
        SERVER_ADDRESS = ("192.168.11.157", 60000)
        client_socket.connect(SERVER_ADDRESS)
        connected = True
    except ConnectionRefusedError as e:
        print(f"连接出异常", e)
    else:
        # 开启一个线程用于接受服务器消息
        t_recv = threading.Thread(target=t_recv_main, args=(client_socket,))
        t_recv.start()

        # 发送消息
        while True:
            send_msg = input("输入发送内容")
            if send_msg == "exit":
                client_socket.close()
                break
            else:
                if connected:
                    send_bytes = send_msg.encode("gbk")
                    client_socket.send(send_bytes)
                    print(f"发送成功")
                else:
                    print(f"已断开 不能发送消息")
                    break





if __name__ == '__main__':
    main()


